package com.example.addressbook.controller;


import com.example.addressbook.entities.Grouping;
import com.example.addressbook.service.GroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping("addGroup")
public class GroupingController {

    @Autowired
    GroupService groupService;

//新建组
    @GetMapping("/new")
    public String new_group(Model model){
        Grouping g1=new Grouping();
        model.addAttribute("group",g1);
        return "new-groups";
    }

//保存新建组
    @PostMapping("/save")
    public String save_group(Model model, Grouping group){
        groupService.save(group);
        return "redirect:/addGroup/new";
    }

//list组列表
    @GetMapping("/display")
    public String display_group(Model model){
        List<Grouping> groups = groupService.findAll();
        model.addAttribute("groups",groups);
        return "display_group";
    }

   //更新组
    @GetMapping("/update")
    public String displayGroupUpdateForm(@RequestParam("id")long thId,Model model){
        Grouping thGroup = groupService.findById(thId);
        model.addAttribute("group",thGroup);
        return "new-groups";
    }

    //删除组
    @GetMapping("/delete")
    public String deleteGroup(@RequestParam("id")long thId,Model model){
        Grouping thGroup = groupService.findById(thId);
        groupService.delete(thGroup);
        return "redirect:/addGroup/display";
    }



}
